import bookmarkServer from '../../../../server/bookmark/bookmarkServer'

let quantity = require('../../../../common/quantity')

let { action, mutation } = quantity

const uuid = require('uuid/v4')

const state = {
  bookmarks: [],
  historys: {
    dossier: {},
    docDossier: {}
  }
}

const mutations = {
  [mutation.bookmark.saveBookmark] (state, bookmark) {
    for (let i = 0; i < state.bookmarks.length; i++) {
      let _bookmark = state.bookmarks[i]
      if (_bookmark.nodeid === bookmark.nodeid || _bookmark.bmid === bookmark.bmid) {
        _bookmark.bmname = bookmark.bmname
        _bookmark.bmid = bookmark.bmid
        _bookmark.rootid = bookmark.rootid
        _bookmark.nodeid = bookmark.nodeid
        _bookmark.bmtype = bookmark.bmtype
        return
      }
    }
    state.bookmarks.push(bookmark)
  },
  [mutation.bookmark.deleteBookmark] (state, bmid) {
    for (let i = 0; i < state.bookmarks.length; i++) {
      let bookmark = state.bookmarks[i]
      if (bookmark.bmid === bmid) {
        state.bookmarks.splice(i, 1)
        return
      }
    }
  },
  [mutation.bookmark.saveHistory] (state, historys) {
    state.historys.docDossier = {}
    state.historys.dossier = {}
    historys.map((item) => {
      state.historys[item.bmtype] = { rootid: item.rootid, nodeid: item.nodeid, cjsj: item.cjsj || new Date().getTime() }
    })
  },
  setBookmarks (state, bookmarks) {
    state.bookmarks = bookmarks
  }
}

const actions = {
  async [action.bookmark.getBookmark] ({ commit, dispatch }) {
    let bookmarks = await bookmarkServer.getBookmark()
    let historys = bookmarks.filter((item) => item.bmtype === item.bmid)
    commit(mutation.bookmark.saveHistory, historys)
    commit('setBookmarks', bookmarks)
  },
  async [action.bookmark.saveBookmark] ({ commit, dispatch, rootState }, { bmid, rootid, nodeid, bmname, bmtype, cjsj = '' }) {
    bmid = bmid || uuid()

    let bookmarks = await bookmarkServer.saveBookmark(bmid, rootid, nodeid, bmname, bmtype, cjsj)

    if (bookmarks) commit(mutation.bookmark.saveBookmark, { bmid, rootid, nodeid, bmname, bmtype })

    console.log('saveBookmark', bookmarks)

    return bookmarks
  },
  async [action.bookmark.deleteBookmark] ({ commit, dispatch }, bmid) {
    let bookmarks = await bookmarkServer.deleteBookmark(bmid)
    console.log('deleteBookmark', bookmarks)
    if (bookmarks) commit(mutation.bookmark.deleteBookmark, bmid)
    return bookmarks
  },
  async [action.bookmark.saveHistory] ({ commit, dispatch }, { rootid, nodeid, bmtype }) {
    let save = await bookmarkServer.saveHistory(rootid, nodeid, bmtype)
    // if (save) commit(mutation.bookmark.saveHistory, [{rootid, nodeid, bmtype}]);
    return save
  }
}
const getters = {
  getBookmark (state, getter, store) {
    return (nodeid) => state.bookmarks.find((item) => item.nodeid === nodeid && item.bmid !== item.bmtype)
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
